/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.gson.Gson;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.mapper.AchievementsMapper;
import com.jeeplus.modules.infor.mapper.GoodsCustomerMapper;
import com.jeeplus.modules.infor.mapper.PriceCustomersMapper;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.infor.service.NewCustomersService;

/**
 * 下游客户Controller
 * @author 李超辉
 * @version 2019-04-28
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/newCustomers")
public class NewCustomersController extends BaseController {

	@Autowired
	private NewCustomersService newCustomersService;
	@Autowired
    private PriceCustomersMapper priceCustomersMapper;
	@Autowired
    private GoodsCustomerMapper goodsCustomerMapper;
	@Autowired
    private AchievementsMapper achievementsMapper;
	
	@ModelAttribute
	public NewCustomers get(@RequestParam(required=false) String id) {
		NewCustomers entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = newCustomersService.get(id);
		}
		if (entity == null){
			entity = new NewCustomers();
		}
		return entity;
	}
	@RequestMapping("getLnCustomersByName")
	@ResponseBody
	public  String getLnCustomersByName(String name,String pro){
		NewCustomers r=new NewCustomers();
		r.setSite(name);
		r.setPro(UserUtils.getUseroffice());
		List<NewCustomers> list=newCustomersService.findList(r);
		Gson gson=new Gson();
		return gson.toJson(list).toString();
	}
	@RequestMapping("det")
	@ResponseBody
	public NewCustomers det(String i){
		return newCustomersService.get(i);
	}
	/**
	 * 下游客户列表页面
	 */
	@RequiresPermissions("infor:newCustomers:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/newCustomersList";
	}
	
		/**
	 * 下游客户列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:newCustomers:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(NewCustomers newCustomers, HttpServletRequest request, HttpServletResponse response, Model model) {
	String pro=UserUtils.getUseroffice();
	if(!pro.equals("总部")){
		newCustomers.setPro(pro);
	}
			Page<NewCustomers> page = newCustomersService.findPage(new Page<NewCustomers>(request, response), newCustomers);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑下游客户表单页面
	 */
	@RequiresPermissions(value={"infor:newCustomers:view","infor:newCustomers:add","infor:newCustomers:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(NewCustomers newCustomers, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			newCustomers.setPro(pro);
		}
		model.addAttribute("newCustomers", newCustomers);
		return "modules/infor/newCustomersForm";
	}

	/**
	 * 保存下游客户
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:newCustomers:add","infor:newCustomers:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(NewCustomers newCustomers, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, newCustomers)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		//新增或编辑表单保存
		newCustomersService.save(newCustomers);//保存
		j.setSuccess(true);
		j.setMsg("保存下游客户成功");
		return j;
	}
	
	/**
	 * 删除下游客户
	 */
	@ResponseBody
	@RequiresPermissions("infor:newCustomers:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(NewCustomers newCustomers, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		newCustomersService.delete(newCustomers);
		j.setMsg("删除下游客户成功");
		return j;
	}
	
	/**
	 * 批量删除下游客户
	 */
	@ResponseBody
	@RequiresPermissions("infor:newCustomers:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			newCustomersService.delete(newCustomersService.get(id));
		}
		j.setMsg("删除下游客户成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
    @RequestMapping(value = "export", method=RequestMethod.GET)
    public AjaxJson exportFile(NewCustomers newCustomers, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String pro=UserUtils.getUseroffice();
		if(!"总部".equals(pro)){
			newCustomers.setPro(pro);
		}
		try {
            String fileName = "下游客户"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<NewCustomers> page = newCustomersService.findPage(new Page<NewCustomers>(request, response, -1), newCustomers);
    		new ExportExcel("下游客户", NewCustomers.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出下游客户记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "export1", method=RequestMethod.GET)
	public AjaxJson exportFile1(PriceCustomers newCustomers, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String pro=UserUtils.getUseroffice();
		if(!"总部".equals(pro)){
			newCustomers.setPro(pro);
		}
		try {
			String fileName = "运输价格"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
		List<PriceCustomers> page = priceCustomersMapper.findList(newCustomers);
			new ExportExcel("运输价格", PriceCustomers.class).setDataList(page).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出下游客户记录失败！失败信息："+e.getMessage());
		}
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "export2", method=RequestMethod.GET)
	public AjaxJson exportFile2(Achievements newCustomers, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String pro=UserUtils.getUseroffice();
		if(!"总部".equals(pro)){
			newCustomers.setPro(pro);
		}
		try {
			String fileName = "绩效运价"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			List<Achievements> page = achievementsMapper.findList(newCustomers);
			new ExportExcel("绩效运价", Achievements.class).setDataList(page).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出下游客户记录失败！失败信息："+e.getMessage());
		}
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "export3", method=RequestMethod.GET)
	public AjaxJson exportFile3(GoodsCustomer newCustomers, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String pro=UserUtils.getUseroffice();
		if(!"总部".equals(pro)){
			newCustomers.setPro(pro);
		}
		try {
			String fileName = "物料上浮"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			List<GoodsCustomer> page = goodsCustomerMapper.findList(newCustomers);
			new ExportExcel("物料上浮", GoodsCustomer.class).setDataList(page).write(response, fileName).dispose();
			j.setSuccess(true);
			j.setMsg("导出成功！");
			return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出下游客户记录失败！失败信息："+e.getMessage());
		}
		return j;
	}


	@ResponseBody
    @RequestMapping(value = "detail")
	public NewCustomers detail(String id) {
		return newCustomersService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:newCustomers:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<NewCustomers> list = ei.getDataList(NewCustomers.class);
			for (NewCustomers newCustomers : list){
				try{
					newCustomersService.save(newCustomers);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			ImportExcel ei1 = new ImportExcel(file, 1, 1);
			List<PriceCustomers> list3 = ei1.getDataList(PriceCustomers.class);
			ImportExcel ei2 = new ImportExcel(file, 1, 2);
			List<GoodsCustomer> list2 = ei2.getDataList(GoodsCustomer.class);
			ImportExcel ei3 = new ImportExcel(file, 1, 3);
			List<Achievements> list1 = ei3.getDataList(Achievements.class);

            for (PriceCustomers n : list3){
                try{
                    n.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    priceCustomersMapper.insert(n);
                    successNum++;
                }catch(ConstraintViolationException ex){
                    failureNum++;
                }catch (Exception ex) {
                    failureNum++;
                }
            }
            for (GoodsCustomer n : list2){
                try{
                    n.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    goodsCustomerMapper.insert(n);
                    successNum++;
                }catch(ConstraintViolationException ex){
                    failureNum++;
                }catch (Exception ex) {
                    failureNum++;
                }
            }
            for (Achievements n : list1){
                try{
                    n.setId(UUID.randomUUID().toString().replaceAll("-",""));
                    achievementsMapper.insert(n);
                    successNum++;
                }catch(ConstraintViolationException ex){
                    failureNum++;
                }catch (Exception ex) {
                    failureNum++;
                }
            }
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入下游客户失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/newCustomers/?repage";
    }
	
	/**
	 * 下载导入下游客户数据模板
	 */
	@RequiresPermissions("infor:newCustomers:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "下游客户数据导入模板.xlsx";
    		List<NewCustomers> list = Lists.newArrayList(); 
    		new ExportExcel("下游客户数据", NewCustomers.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/newCustomers/?repage";
    }
	/**
	 * 下载导入下游客户数据模板
	 */
	@RequiresPermissions("infor:newCustomers:import")
	@RequestMapping(value = "import/template2")
	public String importFileTemplate1(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "物料调整.xlsx";
			List<NewCustomers> list = Lists.newArrayList();
			new ExportExcel("物料调整", GoodsCustomer.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/newCustomers/?repage";
	}
	/**
	 * 下载导入下游客户数据模板
	 */
	@RequiresPermissions("infor:newCustomers:import")
	@RequestMapping(value = "import/template3")
	public String importFileTemplate2(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "绩效运价.xlsx";
			List<NewCustomers> list = Lists.newArrayList();
			new ExportExcel("绩效运价", Achievements.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/newCustomers/?repage";
	}
	/**
	 * 下载导入下游客户数据模板
	 */
	@RequiresPermissions("infor:newCustomers:import")
	@RequestMapping(value = "import/template1")
	public String importFileTemplate3(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "运输价格.xlsx";
			List<NewCustomers> list = Lists.newArrayList();
			new ExportExcel("运输价格", PriceCustomers.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/newCustomers/?repage";
	}

}